//
//  BHCircleChosePlaceAreaViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/14.
//

import UIKit
import AMapSearchKit
@objc protocol BHCircleChosePlaceAreaViewControllerDelegate: NSObjectProtocol {
    func didChoseAddress(poi: AMapPOI?)
}

class BHCircleChosePlaceAreaViewController: BHBaseViewController {

    var delegate: BHCircleChosePlaceAreaViewControllerDelegate?
    
    
    lazy var searchAPI: AMapSearchAPI = {
        let searchapi = AMapSearchAPI.init()
        searchapi!.delegate = self
        return searchapi!
    }()
    
    lazy var navigationBar_view: BHCircleChoseAreaNavigationBar = {
        let view = BHCircleChoseAreaNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCircleChoseAreaNavigationBar.secHeight)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.frame = CGRect(x: 0, y: BHCircleChoseAreaNavigationBar.secHeight, width: UIScreen.width, height: UIScreen.height-BHCircleChoseAreaNavigationBar.secHeight)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .color_f8f8f8
        view.regiseterNib(nibName: "BHCircleNeverShowPlaceCell")
        view.regiseterNib(nibName: "BHCircleChosePlaceAreaCell")

        return view
    }()
    
    weak var weakSuper: BHBaseViewController?
    
    fileprivate var searchKey: String = ""
    fileprivate var addressArray: [AMapPOI] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.navigationBar_view)
        self.view.addSubview(self.tableView)
      
        
        self.navigationBar_view.back_btn.addBtnAction(action: {[weak self] (_) in
            self?.navigationController?.popViewController(animated: true)
        }, for: .touchUpInside)
        
        self.navigationBar_view.searchBackView.addBtnAction(action: {[weak self] (_) in
            self?.goSearch()
        }, for: .touchUpInside)
        
        
        // 开启周边搜索
        self.startSearchAround()
    }
    
    private func goSearch() {
        let searchVC = BHCircleSearchAreaViewController.init()
        searchVC.weakSuper = self.weakSuper
        searchVC.delegate = self
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    
    private func startSearchAround() {
        
        // 逆地理编码
        let request = AMapReGeocodeSearchRequest.init()
        request.location = AMapGeoPoint.location(withLatitude: BHLocationManager.shared.latitude_float, longitude: BHLocationManager.shared.longitude_float)
        self.searchAPI.aMapReGoecodeSearch(request)
        
        // 周边搜索
        let aroundRequest = AMapPOIAroundSearchRequest.init()
        aroundRequest.location = AMapGeoPoint.location(withLatitude: BHLocationManager.shared.latitude_float, longitude: BHLocationManager.shared.longitude_float)
        aroundRequest.types = "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
        aroundRequest.sortrule = 0
        aroundRequest.offset = 25
        aroundRequest.requireExtension = true
        self.searchAPI.aMapPOIAroundSearch(aroundRequest)
    }
    
}

extension BHCircleChosePlaceAreaViewController {
    func transPoi(tip: AMapTip) -> AMapPOI  {
        let poi = AMapPOI.init()
        poi.name = tip.name
        poi.address = tip.address
        poi.location = tip.location
        var provinceRange: NSRange = NSMakeRange(0, 0)
        
        
        if tip.district.contains("省") == true {
            provinceRange = tip.district.findTextRange(text: "省")
            let provinceName = tip.district.id_subString(to: provinceRange.location+1)
            poi.province = provinceName
        }
        
        var cityRange: NSRange = NSMakeRange(0, 0)
        if tip.district.contains("市") == true {
            cityRange = tip.district.findTextRange(text: "市")
            let cityName = tip.district.id_subString(from: provinceRange.location+provinceRange.length, offSet: cityRange.location-(provinceRange.location+provinceRange.length)+1)
            poi.city = cityName
            
        }
        
        let areaName = tip.district.id_subString(from: cityRange.location+cityRange.length)
        poi.district = areaName
        return poi
    }
}


extension BHCircleChosePlaceAreaViewController: BHCircleSearchAreaViewControllerDelegate {
    func didSearchAreaChose(tip: AMapTip?) {
        if tip == nil {
            return
        }
        let poi = self.transPoi(tip: tip!)
        self.delegate?.didChoseAddress(poi: poi)
    }
}


extension BHCircleChosePlaceAreaViewController: AMapSearchDelegate {
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        
    }
    
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        if self.addressArray.count != 0 {
            self.addressArray.removeAll()
        }
        self.addressArray.append(contentsOf: response.pois)
        self.tableView.reloadData()
    }
}

extension BHCircleChosePlaceAreaViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return self.addressArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 45
        }
        return 65
    }
 
    
    
}

extension BHCircleChosePlaceAreaViewController: UITableViewDelegate {

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleNeverShowPlaceCell", for: indexPath) as! BHCircleNeverShowPlaceCell
          
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleChosePlaceAreaCell", for: indexPath) as! BHCircleChosePlaceAreaCell
            let poi = self.addressArray[indexPath.row]
            cell.name_label.text = poi.name
            cell.address_label.text = poi.address
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            self.delegate?.didChoseAddress(poi: nil)
        }else {
            let poi = self.addressArray[indexPath.row]
            self.delegate?.didChoseAddress(poi: poi)
        }
        self.navigationController?.popViewController(animated: true)
    }
}
